package com.isaacwaller.digg;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.DataSetObserver;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;


public class DiggStoriesListAdapter extends BaseAdapter {
	
static String TAG = "DiggResponseLA";
	List<JSONObject> response = new ArrayList<JSONObject>();
	Context c;
	String from;
	
	String url;
	String rootElement;
	
	boolean isLoading = false;
	boolean reachEnd = false;

	public boolean areAllItemsEnabled() {
		return true;
	}
	public boolean isEnabled(int arg0) {
		return true;
	}
	public Object getItem(int arg0) {
		return response.get(arg0);
	}
	public long getItemId(int arg0) {
		return 0;
	}
	public int getItemViewType(int arg0) {
		return 0;
	}
	public int getViewTypeCount() {
		return 1;
	}
	public boolean hasStableIds() {
		return false;
	}
	public boolean isEmpty() {
		return response.isEmpty(); 
	}
	public void registerDataSetObserver(DataSetObserver arg0) {
	}
	public void unregisterDataSetObserver(DataSetObserver arg0) {
	}
	
	public List<JSONObject> getList() { return response; }

	DiggStoriesListAdapter(Context c, String url, String rootElement,
			String from, Handler refreshHandler,List<JSONObject> loadList) throws ClientProtocolException, URISyntaxException,
			IOException, JSONException {
		this.c = c;
		this.from = from;
		this.url = url;
		this.rootElement = rootElement;
		if(loadList==null) {
			loadMore(refreshHandler);
		} else {
			response=loadList;
		}
	}
	
	public void loadMore(Handler refreshHandler) throws ClientProtocolException, URISyntaxException,
	IOException, JSONException {
		if(isLoading) { return; } //if is already loading, return.
		isLoading = true;
		notifyDataSetChanged();
		if(refreshHandler!=null) {
			refreshHandler.sendMessage(new Message());
		}
		JSONObject jsonresponse = DiggInterface.makeRequest(url,"&count=10&offset="+response.size());
		Log.v(TAG,"JSON Response: "+jsonresponse.toString());
		Log.i(TAG, "Response completed. Count:"+jsonresponse.getInt("count")+" Timestamp:"+jsonresponse.getInt("timestamp"));
		if(jsonresponse.getInt("count")<10) {
			// Less than 10 responses were sent back, so that means there are no more left to get.
			Log.i(TAG, "Less than 10 responses, setting reachEnd.");
			reachEnd = true;
			if(jsonresponse.getInt("count")==0) {
				//None to parse and add so return.
				isLoading = false;
				notifyDataSetChanged();
				if(refreshHandler!=null) {
					refreshHandler.sendMessage(new Message());
				}
				return;
			}
		}
		JSONArray array = jsonresponse.getJSONArray(rootElement);
		for (int i = 0; i<array.length(); i++) {
			response.add(array.getJSONObject(i));
		}
		isLoading = false;
		notifyDataSetChanged();
		if(refreshHandler!=null) {
			refreshHandler.sendMessage(new Message());
		}
	}
	
	public int getCount() {
		if(reachEnd) { return response.size(); } //If there are no more diggs to be loaded, don't show the load more button.
		return response.size()+1;
	}
	
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		JSONObject thisjson = null;
		try {
			thisjson = response.get(arg0);
		} catch (IndexOutOfBoundsException e) {
			TextView tv = (TextView)View.inflate(c, R.layout.singleline, null);
			//Doesn't exist, return 'Load more items'
			if(isLoading) { //is loading
				//TODO: Disable the list button here/make text darker/spinner thingy/something to indicate it is loading.
				tv.setText(R.string.loading); 
			} else {
				tv.setText(R.string.loadmoreitems); //not loading, give option to load more
			}
			
			return tv;
		}
		
		
		LinearLayout linearLayout = (LinearLayout)View.inflate(c, R.layout.story, null);
		
		
		TextView title = (TextView)linearLayout.findViewById(R.id.name);
		TextView desc = (TextView)linearLayout.findViewById(R.id.desc);
		TextView diggs = (TextView)linearLayout.findViewById(R.id.diggs);
		
		try {
			title.setText(thisjson.getString(from));
			String description  = thisjson.getString("description");
			if(description==null || description.length()==0) {
				desc.setVisibility(View.GONE);
			} else {
				desc.setText(description);
			}
			diggs.setText(""+thisjson.getInt("diggs"));
		} catch (JSONException e) {
			Log.e(null,e.toString());
			return null;
		}
		return linearLayout;
	}

}
